package com.zyy.service;

import com.alibaba.fastjson2.JSON;
import com.zyy.pojo.Goods;
import com.zyy.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 类描述
 * @Author: zyy
 * @Date: 2023/05/12 18:43
 */
@Service
public class GoodsService {

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;


    public Boolean parseContent(String keyword) throws Exception {

        List<Goods> goodsList = HtmlParseUtil.getGoodsList(keyword);

        BulkRequest request = new BulkRequest();

        for (int i = 0; i < goodsList.size(); i++) {
            Goods goods = goodsList.get(i);

            IndexRequest indexRequest = new IndexRequest("jd-goods");
            indexRequest.id("" + i);
            indexRequest.source(JSON.toJSONString(goods), XContentType.JSON);

            request.add(indexRequest);
        }


        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        return !response.hasFailures();
    }


    public List<Map<String, Object>> search(String keyword, Integer pageNo, Integer pageSize) throws IOException {
        //根据关键字精确查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(termQueryBuilder);
        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);
        //查询超时时间
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        SearchRequest request = new SearchRequest();
        request.source(sourceBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();

        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SearchHit hit : hits.getHits()) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            resultList.add(sourceAsMap);
        }
        return resultList;
    }

    public List<Map<String, Object>> highlightSearch(String keyword, Integer pageNo, Integer pageSize) throws IOException {
        //根据关键字精确查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", keyword);

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(termQueryBuilder);
        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);
        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);
        //查询超时时间
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        SearchRequest request = new SearchRequest();
        request.source(sourceBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();

        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SearchHit hit : hits.getHits()) {
            //sourceAsMap的name是原数据，不会高亮，下面需要做一下替换
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //获取name，这里是高亮处理后的
            HighlightField nameHighlightField = hit.getHighlightFields().get("name");
            if (nameHighlightField != null) {
                Text[] fragments = nameHighlightField.fragments();
                StringBuilder sb = new StringBuilder();
                for (Text fragment : fragments) {
                    sb.append(fragment.string());
                }
                sourceAsMap.put("name", sb.toString());
            }

            resultList.add(sourceAsMap);
        }
        return resultList;
    }
}
